package com.cci.kangdao.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.azureBlob.AzureBlobTool;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.AppVersionT;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.FeedbackService;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.utilTool.*;
import com.gexin.fastjson.JSON;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.Collator;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户反馈业务
 * 
 * @author fengshuai
 *
 */
@Service("FeedbackService")
public class FeedbackServiceImpl implements FeedbackService {
	private Logger log = Logger.getLogger(this.getClass().getName());

	@Autowired
	private UserFeedbackDao userFeedbackDao;
	@Autowired
	private LoginDao loginDao;
	@Autowired
	private PropertiesUtils propertiesUtils;
	@Autowired
	private RedisClientUtils redisClientUtils;
	@Autowired
	private NotifyRecordTDao notifyRecordTDao;
	@Resource
	private RolesNotifyRecordTDao rolesNotifyRecordTDao;
	@Resource
	private MailBoxTDao mailBoxTDao;
	@Resource
	private GMApplyRecordTDao gmApplyRecordTDao;
	@Resource
	private WorkOrderDrDao workOrderDrDao;
	@Resource
	private CommonNotifyRecordTDao commonNotifyRecordTDao;
    @Resource
	private NotifyRecordDYDao notifyRecordDYDao;
    @Resource
	private UserTDao userTDao;
    @Resource
	private FileUploadMsgTDao fileUploadMsgTDao;
    @Resource
    private SMNTDao smntDao;
	@Resource
	private WorkOrderTDao workOrderTDao;
	@Resource
	private SSRepairTDao ssRepairTDao;
	@Resource
	private DictionariesTDao dictionariesTDao;



	/**
	 * App意见反馈接口
	 */
	@Override
	public ModelAndView submitFeedback(Map<String, Object> map) {
		// problemType 意见类型 String
		// problemFun 意见反馈功能 String
		// problemEngine 意见反馈机型 String
		// content 意见反馈内容 String
		// phone 联系电话 String
		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			JSONObject obj = new JSONObject();
			/**
			 * 判断意见类型problemType是否为空
			 */
			if (map.get("problemType") == null || map.get("problemType").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			// 意见反馈内容content是否为null
			if (map.get("content") == null) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			// 联系电话phone是否为null
			if (map.get("phone") == null || map.get("phone").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}

			/**
			 * 1、查询用户信息
			 */
			String userid = request.getHeader("userid");
			/**
			 * 如果是空的话就是游客userid存入是0
			 */
			if (userid != null ) {
				userid = AESTool.decryptString(userid);// 解密userid
				/**
				 * 根据userid 查询出user表的id
				 */
				UserT userT = (UserT) redisClientUtils.getObject("userT" + userid);
				map.put("userid", userT.getId());
			} else {
				map.put("userid", 0);
			}
			/*
			 * problemFun 意见反馈功能 problemEngine 意见反馈机型
			 */
			if (map.get("problemFun") == null || map.get("problemFun").toString().equals("")) {
				map.put("problemFun", "");
			}
			if (map.get("problemEngine") == null || map.get("problemEngine").toString().equals("")) {
				map.put("problemEngine", "");
			}
			//
			int i = userFeedbackDao.submitFeedback(map);
			if (i > 0) {
				obj.put("status", 0);
				obj.put("msg", "");
			} else {
				obj.put("status", -99);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));
			}
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * App用户获取app版本接口
	 */
	@Override
	public ModelAndView getAppVersion(Map<String, Object> map) {

		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			String eAppVersion = request.getHeader("EAppVersion");
			JSONObject obj = new JSONObject();
			/**
			 * 判断TYpe 0是Android，1是iso，默认0
			 */
			if (map.get("type") == null || map.get("type").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			obj.put("status", 0);
			obj.put("msg", "");
			UserT userT = null;
			String userid = request.getHeader("userid");
			if(StringUtils.isNotBlank(userid)) {
				userT = userTDao.selectById(Long.valueOf(AESTool.decryptString(userid)));
				if(null != userT){
					int i = userTDao.isEndUser(userT.getId());
					if (i >0) {
						map.put("userRole", 1);
					} else {
						map.put("userRole", 2);
					}
				}
			}
			if(StringUtils.isBlank(eAppVersion)){
				eAppVersion = "2.0.7";
			}
			map.put("eAppVersion", eAppVersion);
			log.info("App用户获取升级参数："+map);
			List<AppVersionT> appVersionList = userFeedbackDao.getAppVersionPlus(map);
			if (CollectionUtils.isNotEmpty(appVersionList)) {
				AppVersionT appVersion = appVersionList.get(0);
				String versionNumMin = appVersion.getVersionNumMin();
				List<String> frameFunction = new ArrayList<>();
				int isPopup = -1;//弹窗标记 0-弹窗 -1不弹
				Set<Long> frameFunctionIds = new HashSet<>();
				//升级弹窗位置集合
				for(AppVersionT appVersionT : appVersionList){
					if(StringUtils.isNotBlank(appVersionT.getFrameFunctionIds())){
						String[] split = appVersionT.getFrameFunctionIds().split(",");
						for (String s : split) {
							if(StringUtils.isNotBlank(s)){
								frameFunctionIds.add(Long.parseLong(s));
							}
						}
					}
					if(StringUtils.isNotBlank(appVersionT.getVersionNumMin()) && appVersionT.getVersionNumMin().compareTo(versionNumMin) > 0){
						versionNumMin = appVersionT.getVersionNumMin();
					}
				}

				if(null != userT && null != appVersion.getFrameRate() && CollectionUtils.isNotEmpty(frameFunctionIds)){
					frameFunction = getFrameFunction(new ArrayList<>(frameFunctionIds));

					//查询忽略提醒的时间
					Map<String, Object> ignoreUpgradeRecordById = getIgnoreUpgradeRecordById(userT.getId());
					if(null != ignoreUpgradeRecordById && !ignoreUpgradeRecordById.isEmpty()){
						String ignoreTime = (String)ignoreUpgradeRecordById.get("ignoreTime");
						//当前时间
						String nowTime = Date_Util.getNowTime();
						//升级时间
						String versionTime = Date_Util.addHour(appVersion.getSystime(), 8);
						//忽略提醒的时间
						String expireTime = Date_Util.addHour(ignoreTime, appVersion.getFrameRate());

						if(LocalTimeUtil.isBefore(versionTime,ignoreTime) && LocalTimeUtil.isBefore(expireTime,nowTime)){
							isPopup = 0;
						} else if (LocalTimeUtil.isBefore(ignoreTime,versionTime)) {
							isPopup = 0;
						}
					} else {
						isPopup = 0;
					}
				}
				String description = appVersion.getDescription();
				if(appVersionList.size() > 1){
					description = dictionariesTDao.getListByDTableNameAndDInt("appVersionDesc","0");
				}
				obj.put("isPopup", isPopup);
				obj.put("userRole", appVersion.getUserRole());
				obj.put("frameRate", appVersion.getFrameRate());
				obj.put("frameFunctionIds", frameFunction);
				obj.put("versionNum", appVersion.getVersionNum());
				obj.put("versionNumMin", versionNumMin);
				obj.put("appUrl", appVersion.getAppUrl());
				obj.put("iosUrl", appVersion.getIosUrl());
				obj.put("description", description);
			} else {
				obj.put("isPopup", -1);
				obj.put("userRole", "");
				obj.put("frameRate", 0);
				obj.put("frameFunctionIds", new ArrayList<String>());
				obj.put("versionNum", "");
				obj.put("versionNumMin", "");
				obj.put("appUrl", "");
				obj.put("iosUrl", "");
				obj.put("description", "");
			}
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	@Override
	public boolean addUserIgnoreUpgradeRecord(UserT userT, String nowTime) {
		Map<String, Object> map = new HashMap<>();
		map.put("userId",userT.getId());
		map.put("ignoreTime",nowTime);
		map.put("creator",userT.getId());
		map.put("createTime",nowTime);
		map.put("updator",userT.getId());
		map.put("updateTime",nowTime);
		map.put("flag",0);
		int i = userFeedbackDao.addUserIgnoreUpgradeRecord(map);
		return i > 0;
	}

	@Override
	public Map<String, Object> getIgnoreUpgradeRecordById(Long userId) {
		Map<String, Object> ignoreUpgradeRecordById = userFeedbackDao.getIgnoreUpgradeRecordById(userId);
		return ignoreUpgradeRecordById;
	}

	/*
	 * @description: 获取APP升级弹框功能表
	 * @param: frameFunctionIds
	 * @return: List<String>
	 * @author: yinguili
	 * @date: 2022/9/8 15:45
	 */
	@Override
	public List<String> getFrameFunction(List<Long> frameFunctionIds) {
		List<String> FunctionIds = userFeedbackDao.getFrameFunction(frameFunctionIds);
		return FunctionIds;
	}

	@Override
	public ModelAndView getFeedBackMD(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		String userid = request.getHeader("userid");
		JSONObject obj = new JSONObject();
		try {
			
			// 问题类型
			List<Map<String, Object>> ptMaps = userFeedbackDao.getPromType();
			
			// 反馈渠道
			List<Map<String, Object>> ugMaps = userFeedbackDao.getUserGroup();
			
			// 反馈功能
			List<Map<String, Object>> funMaps = userFeedbackDao.getFunList();
			//根据 首字符排序
			Comparator comparator = Collator.getInstance(Locale.CHINA);
			List<Map<String, Object>> dValueMaps = funMaps.stream().sorted((er, et) -> {
						String dValue1 = (String) er.get("DValue");
						String dValue2 = (String) et.get("DValue");
						return comparator.compare(dValue1, dValue2);
					}
			).collect(Collectors.toList());
			
			// 咨询机型
			List<Map<String, Object>> etMaps = userFeedbackDao.getEngineTypeList();
			//查询smn
            List<Map<String, Object>> smnList = smntDao.getDintDvalueSMNList(null);
			// 查询最后一个工单的机型
//			Long userId = MapUtils.getLong(map, "userId");
			String lastSMNWorkorder = "";
            String lastSMNCDSWorkorder = "";
			if (StringUtils.isNotBlank(userid)) {
				String userId = AESTool.decryptString(userid);
				//查询是否是终端用户
				Integer hasRoleCount = userTDao.getUserCountByRoleAndUserId("R0002", Long.valueOf(userId));
				if (hasRoleCount != null && hasRoleCount > 0) {
					lastSMNWorkorder = workOrderTDao.getLastSMNWorkorder(Long.valueOf(userId));
				} else {
					lastSMNWorkorder = workOrderTDao.getLastSMNWorkorderByPrincipal(Long.valueOf(userId));
				}
				lastSMNCDSWorkorder = workOrderDrDao.getLastSMNCDSWorkorder(Long.valueOf(userId));
			}
			obj.put("problemType", ptMaps);
			obj.put("userGroup", ugMaps);
			obj.put("functionList", dValueMaps);
			obj.put("engineType", etMaps);
            obj.put("smnList", smnList);
            obj.put("lastSMNWorkorder", StringUtils.isBlank(lastSMNWorkorder) ? "" : lastSMNWorkorder);
            obj.put("lastSMNCDSWorkorder", StringUtils.isBlank(lastSMNCDSWorkorder) ? "" : lastSMNCDSWorkorder);

			obj.put("status", 0);
			obj.put("msg", "");
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			log.error(e.getMessage(), e);
			try {
				obj.put("status", -99);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));
				ParameterTool.writeResponse(response, obj.toString());
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		return null;
	}

	@Override
	@Transactional
	public ModelAndView submitFeedbackV4(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		String userid = request.getHeader("userid");
		try {
			JSONObject obj = new JSONObject();
			/**
			 * 判断意见类型problemType是否为空
			 */
//			if (map.get("problemType") == null || map.get("problemType").toString().equals("")) {
//				obj.put("status", -5);
//				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
//
//				// 返回客户
//				ParameterTool.writeResponse(response, obj.toString());
//				obj = null;
//				return null;
//			}
			// 反馈渠道
//			if (map.get("userGroup") == null || map.get("userGroup").toString().equals("")) {
//				obj.put("status", -5);
//				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
//
//				// 返回客户
//				ParameterTool.writeResponse(response, obj.toString());
//				obj = null;
//				return null;
//			}
			// 意见反馈内容content是否为null
			if (map.get("content") == null) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			// 联系电话phone是否为null
			if (map.get("phone") == null || map.get("phone").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
            // SMN 为空
//            if (map.get("SMN") == null || map.get("SMN").toString().equals("")) {
//                obj.put("status", -5);
//                obj.put("msg", "请输入SMN");
//
//                // 返回客户
//                ParameterTool.writeResponse(response, obj.toString());
//                obj = null;
//                return null;
//            }
			/**
			 * 1、查询用户信息
			 */

			/**
			 * 如果是空的话就是游客userid存入是0
			 */
			map.put("acceptChannelStr", "");
			if (StringUtils.isNotBlank(userid)) {
				userid = AESTool.decryptString(userid);// 解密userid
				/**
				 * 根据userid 查询出user表的id
				 */
				UserT userT = (UserT) redisClientUtils.getObject("userT" + userid);
				
				if(null == userT) {
					userT = loginDao.getUserByid(userid);
					int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
					redisClientUtils.setObject("userT"+userT.getId(), userT, redisCacheTime);
				}
				if (0 == userT.getCompanyId()) {
					String companyName = ssRepairTDao.getCompanyNameByServiceStationId(userT.getServiceStationID());
					map.put("acceptChannelStr", companyName);
				} else {
					map.put("acceptChannelStr", userT.getCompanyName());
				}
				
				map.put("userid", userT.getId());
			} else {
				map.put("userid", 0);
			}
			/*
			 * problemFun 意见反馈功能 problemEngine 意见反馈机型
			 */
			if (map.get("problemFun") == null || map.get("problemFun").toString().equals("")) {
				map.put("problemFun", "");
			}
			if (map.get("problemEngine") == null || map.get("problemEngine").toString().equals("")) {
				map.put("problemEngine", "");
			}
			// 受理渠道
			map.put("acceptChannel", 0);
			// 订单状态
			map.put("billStatus", 0);
			// 是否已读
			map.put("readFlag", 1);
			// 工单编号
			map.put("billNo", getBillNoSyn());

			// 加锁处理，避免发生多次提交。
			if(!redisClientUtils.lock("submitFeedbackV4-" + userid,60L)){
				ParameterTool.writeErrorResponse(response,-98);
				return null;
			}

			// 数据入库
			String feedBackPhoto = MapUtils.getString(map,"feedBackPhoto","");
			map.put("feedBackPhoto",feedBackPhoto);
            int i = userFeedbackDao.submitFeedbackV5(map);
			if (i > 0) {
				obj.put("status", 0);
				obj.put("msg", "");
			} else {
				obj.put("status", -99);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));
			}
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}finally {
			redisClientUtils.delkey("submitFeedbackV4-" + userid);
		}
		
		return null;
	}

	//上传图片接口
	@Transactional
	@Override
	public ModelAndView fileUpload(Map<String, Object> map){
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		//判断路径下有没有文件夹
		String basePath = request.getSession().getServletContext().getRealPath(propertiesUtils.getPropertiesValue("upload").trim());
		File imgFile = new File(basePath);
		if(!imgFile.exists()){
			imgFile.mkdirs();
		}
		imgFile = null;
		map.put("basePath", basePath);
		//获取生成的图片名称
		String fileName = Upload_Util.uploadData(map);
		if(!"".equals(fileName)){
			/**
			 * 上传到微软云存储文件
			 */
			String filePath = basePath + File.separator + fileName;
			fileName = AzureBlobTool.uploadBlob(propertiesUtils.getPropertiesValue("accountName").trim(),
					propertiesUtils.getPropertiesValue("blobConnection").trim(),
					propertiesUtils.getPropertiesValue("containerName").trim(),
					filePath);
			log.info("图片地址:"+fileName);
			net.sf.json.JSONObject obj = new net.sf.json.JSONObject();
			obj.put("status",0);
			Map<String,Object> data = new HashMap<>();
			data.put("fileUrl",fileName);
			obj.put("data",data);
			obj.put("msg","success");
			if (StringUtils.isNotEmpty(fileName)) {
//				try {
//					// 删除服务器文件
//					FileUtils.forceDelete(new File(filePath));
//				} catch (IOException e) {
//					log.warn("删除服务器照片失败" + e.getMessage(), e);
//				}
			}
			ParameterTool.writeResponse(response, obj.toString());
		}
		return null;
	}


	//新上传图片接口
	@Transactional
	@Override
	public ModelAndView newFileUpload(Map<String, Object> map){
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		//判断路径下有没有文件夹
		String basePath = request.getSession().getServletContext().getRealPath(propertiesUtils.getPropertiesValue("upload").trim());
		File imgFile = new File(basePath);
		if(!imgFile.exists()){
			imgFile.mkdirs();
		}
		imgFile = null;
		map.put("basePath", basePath);
		//获取生成的图片名称
		String fileName = Upload_Util.newUploadData(map);
		if(!"".equals(fileName)){
			/**
			 * 上传到微软云存储文件
			 */
			String filePath = basePath + File.separator + fileName;
			fileName = AzureBlobTool.uploadBlob(propertiesUtils.getPropertiesValue("accountName").trim(),
					propertiesUtils.getPropertiesValue("blobConnection").trim(),
					propertiesUtils.getPropertiesValue("containerName").trim(),
					filePath);
			log.info("图片地址:"+fileName);
			net.sf.json.JSONObject obj = new net.sf.json.JSONObject();
			obj.put("status",0);
			Map<String,Object> data = new HashMap<>();
			data.put("fileUrl",fileName);
			obj.put("data",data);
			obj.put("msg","success");

			if (StringUtils.isNotEmpty(fileName)) {
				try {
					// 删除服务器文件
					FileUtils.forceDelete(new File(filePath));
				} catch (IOException e) {
					log.warn("删除服务器照片失败" + e.getMessage(), e);
				}
			}

			//将文件地址保存在数据库中
			UserT userT = UserThreadLocal.get();
			Map<String,Object> fileUploadMsgTMap = new HashMap<>();
			if(null != userT){
				fileUploadMsgTMap.put("UserId",userT.getId());
				fileUploadMsgTMap.put("Contact",userT.getContact());
				fileUploadMsgTMap.put("UserName",userT.getUserName());
				fileUploadMsgTMap.put("Creator",userT.getId());
			}else{
				fileUploadMsgTMap.put("UserId",-1);
				fileUploadMsgTMap.put("Contact","");
				fileUploadMsgTMap.put("UserName","");
				fileUploadMsgTMap.put("Creator",-1);
			}
			//目前只有WA错误日志上传用到此接口   所以这块为了后续扩展    预留FileType字段   默认值为1   代表WA错误日志上传
			int fileType = MapUtils.getIntValue(map,"FileType",1);
			fileUploadMsgTMap.put("FileType",fileType);
			fileUploadMsgTMap.put("FileUrl",fileName);
			fileUploadMsgTMap.put("CreateTime",LocalTimeUtil.getRealCurrentTime());
			fileUploadMsgTDao.insertSelective(fileUploadMsgTMap);
			ParameterTool.writeResponse(response, obj.toString());
		}
		return null;
	}

	//不存在服务手册   用户意见反馈
	@Transactional
	@Override
	public ModelAndView notExistHandBookConfigFeedBack(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		JSONObject obj = new JSONObject();
		Map<String,Object> contentJsonMap = JSON.parseObject(MapUtils.getString(map,"contentJson"), Map.class);
		long orderId = MapUtils.getLongValue(contentJsonMap,"OrderId",-1);
		UserT userT = UserThreadLocal.get();
		try {
			Map<String,Object> drWorkOrderMap = workOrderDrDao.getDRWorkOrderById(orderId);
			if(MapUtils.isEmpty(drWorkOrderMap)){
				obj.put("status", -8);
				obj.put("msg", "未获取到诊断工单信息");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			int drWorkOrderType = MapUtils.getIntValue(drWorkOrderMap,"WorkOrderDRType");   //  1是现场工单    2是模拟工单
			//只有现场工单可以意见反馈   2.2.0需求
			if(drWorkOrderType == 2){
				obj.put("status", 0);
				obj.put("msg", "培训模拟工单不保存意见反馈信息");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			Map<String,Object> insertMap = new HashMap<>();
			insertMap.put("userid",userT.getId());
			//1	    业务问题
			insertMap.put("problemType",1);
            //25	其他-----改为智能诊断
            insertMap.put("problemFun", 26);
			insertMap.put("problemEngine",0);
			insertMap.put("content", MapUtils.getString(contentJsonMap,"Content",""));
			insertMap.put("phone",userT.getPhone());
			insertMap.put("billNo",getBillNoSyn());
			insertMap.put("acceptChannel",0);  //（0：APP；1：WEB）
			insertMap.put("userGroup",userT.getUsergroupId());
			insertMap.put("billStatus",1);   //（0：未处理；1：处理中；2：处理完成）
			//获取处理人
			Map<String,Object> dealerMap = userFeedbackDao.getFeedBackDealerBySendFunctionName("notExistHandBookConfigFeedBackDealer");
			if(MapUtils.isNotEmpty(dealerMap)){
				insertMap.put("dealerId",MapUtils.getLongValue(dealerMap,"UserId"));
			}
			insertMap.put("readFlag",1);   //（0：否；1：是。默认为是）
			int i = userFeedbackDao.submitFeedbackV4(insertMap);
			if (i > 0) {
				obj.put("status", 0);
				obj.put("msg", "");
			} else {
				obj.put("status", -99);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));
			}

			//2.5.0需求  反馈问题后增加邮件提醒
			sendMail(MapUtils.getLongValue(dealerMap,"UserId"),insertMap);
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}


	public void sendMail(long receivePersonUserId,Map<String,Object> mailMsgMap){
		log.info("开始推送邮件：接收人id："+receivePersonUserId);
		UserT userT = userTDao.selectById(receivePersonUserId);
		if(null != userT){
			String email = userT.getEmail();  //邮箱
			if(StringUtils.isNotEmpty(email)){
				String billNo = MapUtils.getString(mailMsgMap,"billNo","");  //工单编号
				String feedbackQuestion = MapUtils.getString(mailMsgMap,"content","");//反馈的问题
				String feedBackReport = propertiesUtils.getPropertiesValue("feedBackReport");  //意见反馈的url
				feedBackReport += "&billNo=" + billNo;
				if(StringUtils.isNotEmpty(email)){
					String subject = "e路康明斯工单处理提醒："+ billNo;  //邮件主题
					String content = "<body>尊敬的用户你好:<br><p style='text-indent: 2em;'>您有未处理的工单，请及时处理！</p><p style='text-indent: 2em;'>工单编号：" + billNo+ "</p><p style='text-indent: 2em;'>反馈问题：" + feedbackQuestion + "</p><p style='text-indent: 2em;'><a href='"+feedBackReport+"'>前往移动应用管理平台处理工单</a></p></body>";  //邮件内容
					try {
						MailUtil.sendMail(email,subject, content);  //推送邮件
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}


	/**
	 * 获取工单编号
	 * @return
	 */
	@Override
	public void getBillNo(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		JSONObject obj = new JSONObject();
		try {
			obj.put("billNo", getBillNoSyn());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ParameterTool.writeResponse(response, obj.toString());
	}
	
	public synchronized String getBillNoSyn() {
		// 当天日期
		LocalDate date = LocalDate.now();
		String dateStr = date.toString().replaceAll("-", "");
		
		// 从缓存获取编号和时间戳
		String noStr = redisClientUtils.hget("billNo", dateStr);
		
		int no = 1; // 编号
		Long time = 0l; //时间戳
		
		// 如果缓存中没有数据，则赋初始值；如果已经有数据，则取值缓存数据
		if(StringUtils.isBlank(noStr)) {
			no = 1;
			time = System.currentTimeMillis();
		} else {
			no = Integer.parseInt(noStr.split("@")[0]);
			time = Long.parseLong(noStr.split("@")[1]);
		}
		
		// 取缓存中最新数据与当前数据做比较，如果缓存中时间戳晚于当前时间戳，则重新获取编号；反之直接获取编号并修改缓存中数据
		String noStrNow = redisClientUtils.hget("billNo", dateStr);
		
		if(StringUtils.isBlank(noStrNow)) {
			redisClientUtils.hset("billNo", dateStr, (no + 1) + "@" + time);
			return String.format(dateStr+"%03d", no);
		} else {
			Long timeNow = Long.parseLong(noStrNow.split("@")[1]);
			if(time < timeNow) {
				return getBillNoSyn();
			} else {
				redisClientUtils.hset("billNo", dateStr, (no + 1) + "@" + time);
				return String.format(dateStr+"%03d", no);
			}
		}
		
	}
	
	
	public static void main(String[] args) {
		LocalDate date = LocalDate.now();
		System.out.println(date.toString().replaceAll("-", ""));
		
		LocalTime time = LocalTime.now();
		System.out.println(time.toString());
		
		System.out.println(System.currentTimeMillis());
	}

	@Override
	public void getFeedBackList(Map<String, Object> map) {
		
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		JSONObject obj = new JSONObject();
		
		String userid = request.getHeader("userid");
		
		userid = AESTool.decryptString(userid);// 解密userid
		
		UserT userT = (UserT) redisClientUtils.getObject("userT" + userid);
		
		if(null == userT) {
			userT = loginDao.getUserByid(userid);
			int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
			redisClientUtils.setObject("userT"+userT.getId(), userT, redisCacheTime);
		}
		
		map.put("userId", userT.getId());
		
		// 分页信息
		int page = 1;
		if (map.get("page") != null) {
			page = MapUtils.getInteger(map, "page", 1);
		}
		int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
		
		map.put("start", (page-1)*pagesize);
		map.put("pagesize", pagesize);
		
		try{
			List<Map<String, Object>> list = userFeedbackDao.getFeedBackList(map);
			list.stream().forEach(feedBack -> {
				feedBack.put("systime", feedBack.get("systime").toString().substring(0, 10));
				feedBack.remove("rownum");
			});
			obj.put("status", 0);
			obj.put("msg", "success");
			obj.put("data", list);
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			log.error("获取意见反馈列表接口（getFeedBackList）调用失败！", e);
		}
		
	}

	@Override
	public void getFeedBackInfo(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		JSONObject obj = new JSONObject();

		try {
			// 意见反馈主键
			if (map.get("id") == null || map.get("id").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
			}

			// 查询数据
			Long id = Long.parseLong(map.get("id").toString());
			Map<String, Object> feedBack = userFeedbackDao.getFeedBackInfo(id);
			this.getListParam(feedBack);
			if (null != feedBack) {
				obj.put("status", 0);
				obj.put("msg", "");
				
				// 如果处理完成,或者已关闭，未解决状态的工单，则标记为已读
				if(("2".equals(feedBack.get("billStatus").toString()) || "3".equals(feedBack.get("billStatus").toString()))
						&& "0".equals(feedBack.get("readFlag").toString())) {
					int no = userFeedbackDao.readFeedBack(id);
					if(no > 0) {
						feedBack.put("readFlag", 1);
					}
				}
				
				obj.put("data", feedBack);
			} else {
				obj.put("status", -99);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));
			}
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			log.error("获取意见反馈详情接口（getFeedBackInfo）异常", e);
		}
		
		
	}

	private void getListParam(Map<String, Object> map) {
		// 问题类型
		List<Map<String, Object>> ptMaps = dictionariesTDao.getDictionariesListByDTableName("problemType");
		Map<Long, String> ptcollect = ptMaps.stream().collect(Collectors.toMap(a1 -> Long.valueOf(a1.get("DInt").toString()), a2 -> a2.get("DValue").toString()));
		// AMT问题类型
		List<Map<String, Object>> AMTptMaps = dictionariesTDao.getDictionariesListByDTableName("ecjvProblemType");
		Map<Long, String> AMTptcollect = AMTptMaps.stream().collect(Collectors.toMap(a1 -> Long.valueOf(a1.get("DInt").toString()), a2 -> a2.get("DValue").toString()));
//		for (Map<String, Object> map : feedBackList) {
		if (map.get("type") == null || (map.get("type") != null && Integer.valueOf(map.get("type").toString()) == 1)) {
			if (map.get("problemType") != null) {
				Long problemType = (Long) map.get("problemType");
				if (ptcollect.containsKey(problemType)) {
					map.put("problemType", ptcollect.get(problemType));
				}
			}

		} else if (map.get("type") != null && Integer.valueOf(map.get("type").toString()) == 2) {
			if (map.get("problemType") != null) {
				Long problemType = (Long) map.get("problemType");
				if (AMTptcollect.containsKey(problemType)) {
					map.put("problemType", AMTptcollect.get(problemType));
				}
			}
		} else {
			map.put("problemType", "");
		}
//		}

	}
	@Override
	public void getUnReadMsgCount(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		try{
			JSONObject obj = new JSONObject();
			UserT userT = UserThreadLocal.get();
			int unReadMsgNum = userFeedbackDao.getUnReadMsgCount(userT.getId());
			map.put("receiverId", userT.getId());
			int isReadNotifyRecordNum = notifyRecordTDao.getIsReadNotifyRecordTNumByUserId(map);  //获取登录人未读消息总数
			int roleNotifyRecordNum = rolesNotifyRecordTDao.unReadNotifyCount(userT.getId());
			int unReadMailBoxMessageNum = mailBoxTDao.getUnReadMessageCountByReceiverId(userT.getId());
			int gmUnReadNum = gmApplyRecordTDao.getGMUnReadNum(userT.getId());  //获取GM消息提醒未读数量
			int escalationUnReadNum = commonNotifyRecordTDao.getUnReadCount("1",userT.getId());
			int cbuUnReadNum =  commonNotifyRecordTDao.getUnReadCount("2",userT.getId());
			int dyUnReadNum = notifyRecordDYDao.getDYUnReadNumByUserId(userT.getId());
			int tsrUnReadNum =  commonNotifyRecordTDao.getUnReadCount("3",userT.getId());
			JSONObject numJsonObject = new JSONObject();
			numJsonObject.put("unReadMsgNum", unReadMsgNum);
			numJsonObject.put("isReadNotifyRecordNum", isReadNotifyRecordNum);
			numJsonObject.put("roleNotifyRecordNum", roleNotifyRecordNum);
			numJsonObject.put("unReadMailBoxMessageNum", unReadMailBoxMessageNum);
			numJsonObject.put("gmUnReadNum", gmUnReadNum);
			numJsonObject.put("escalationUnReadNum", escalationUnReadNum);
			numJsonObject.put("cbuUnReadNum", cbuUnReadNum);
			numJsonObject.put("dyUnReadNum", dyUnReadNum);
			numJsonObject.put("tsrUnReadNum", tsrUnReadNum);
			obj.put("status", 0);
			obj.put("msg", "success");
			obj.put("count", numJsonObject);
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			log.error("获取未读信息条数接口（getUnReadMsgCount）调用失败！", e);
			ParameterTool.writeErrorResponse(response);
		}
	}


}
